import 'package:common/base/base_state.dart';
import 'package:common/base/base_stateful_widget.dart';
import 'package:common/constant/constant.dart';
import 'package:common/constant/route_name_config.dart';
import 'package:common/network/code_msg_model.dart';
import 'package:common/utils/sp_util.dart';
import 'package:flutter/material.dart';
import 'package:toast/toast.dart';

import '../model/login_model.dart';
import '../present/login_present.dart';
import 'login_page_body.dart';


typedef OnLogin = void Function(String userName,String pwd);

///登录页面
class LoginPage extends BaseStatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends BaseState<LoginPage> {
  late LoginPageBody _loginPageBody;
  late LoginPresent _loginPresent;

  @override
  void onStateInit() {
    _loginPresent = LoginPresent(this);
  }

  @override
  bool onNeedAppBar() {
    return false;
  }

  @override
  bool onNeedBack() {
    return false;
  }

  @override
  Widget onBodyCreate() {
    _loginPageBody = LoginPageBody();
    return _loginPageBody.createBody(context, (userName,pwd) {
      showDelayLoadingDialog(context);
      _loginPresent.login(userName,pwd);
    });
  }

  @override
  void onFail(CodeMsgModel baseResponseModel) {
    super.onFail(baseResponseModel);
    Toast.show("登陆成功", duration: Toast.lengthLong, gravity: Toast.bottom);
    //https://blog.csdn.net/yyyyyyui68/article/details/133128774
    Navigator.of(context)
        .pushNamedAndRemoveUntil(RouteNameConfig.kMainPage, (Route route) => false);
  }

  @override
  void onSuccess<D>(D d, String apiPath) {
    super.onSuccess(d, apiPath);
    if(d is Map<String, dynamic>) {
      LoginBean loginBean = LoginBean.fromMap(d);
      SpUtil.putString(Constant.userRealNameKey,loginBean.userRealName);
      SpUtil.putString(Constant.userPhoneKey,loginBean.userPhone);
      SpUtil.putString(Constant.userIdKey,loginBean.userId);
      SpUtil.putString(Constant.tokenKey,loginBean.token).then((value) {
        Toast.show("登陆成功", duration: Toast.lengthLong, gravity: Toast.bottom);
        //https://blog.csdn.net/yyyyyyui68/article/details/133128774
        Navigator.of(context)
            .pushNamedAndRemoveUntil(RouteNameConfig.kMainPage, (Route route) => false);
      });
    }
  }
}

